package sz.szsmk.citizencard.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class Md5Util {
    /**
     * 计算MD5并转换为字符串.
     * @param data Hash数据
     * @return     MD5字符串

     */
    public static String hashToString(byte[] data)
    {
        return ByteUtil.toHexString(hash(data));
    }

    /**
     * 计算MD5并转换为字符串.
     * @param data   Hash数据
     * @param offset 开始位置

     * @param length 长度
     * @return       MD5字符串

     */
    public static String hashToString(byte[] data, int offset, int length)
    {
        return hashToString(Arrays.copyOfRange(data, offset, offset + length));
    }

    /**
     * 计算MD5.,MD5失败，返回原始的data byte[]数组
     * @param data Hash数据
     * @return     MD5
     */
    public static byte[] hash(byte[] data)
    {
        try
        {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hashed = digest.digest(data);
            return hashed;
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
            return data;
            //throw new SeverityException("Failed to get md5 algorithm.");
        }
    }

    /**
     * 计算MD5.
     * @param data   Hash数据
     * @param offset 开始位置

     * @param length 长度
     * @return       MD5
     */
    public static byte[] hash(byte[] data, int offset, int length)
    {
        return hash(Arrays.copyOfRange(data, offset, offset + length));
    }

    /**
     * MD5加密,加密失败返回原始data数据
     * @param data
     * @return
     */
    public static String md5Hash(String data)
    {
        if (null == data || data.length()<=0)
        {
            return "";
        }

        try
        {
            return ByteUtil.toHexString(hash(data.getBytes("utf-8")));
        }
        catch (UnsupportedEncodingException e)
        {
            return data;
        }
    }

    public static String md5(String string, String slat) {
//        if (TextUtils.isEmpty(string)) {
//            return "";
//        }

        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest((string + slat).getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}